document.addEventListener('DOMContentLoaded', function() {
    // 图片上传预览功能
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('imageUpload');
    const previewContainer = document.getElementById('previewContainer');
    const uploadIndicator = document.getElementById('uploadIndicator');
    const uploadProgress = document.getElementById('uploadProgress');
    const MAX_IMAGES = 5; // 修改为最多5张图片
    let uploadedImages = [];

    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择变化事件
    fileInput.addEventListener('change', handleFileSelect);

    // 拖拽功能
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', () => {
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        
        if (e.dataTransfer.files.length) {
            handleFiles(e.dataTransfer.files);
        }
    });

    // 处理文件选择
    function handleFileSelect(e) {
        if (e.target.files.length) {
            handleFiles(e.target.files);
        }
    }

    // 处理文件上传
    function handleFiles(files) {
        const filesArray = Array.from(files);
        
        // 检查文件数量
        if (filesArray.length > MAX_IMAGES) {
            alert(`最多只能上传${MAX_IMAGES}张图片`);
            return;
        }
        
        // 清空现有图片
        uploadedImages = [];
        previewContainer.innerHTML = '';
        
        // 模拟上传进度
        uploadArea.classList.add('uploading');
        let progress = 0;
        const interval = setInterval(() => {
            progress += 5;
            if (progress >= 100) {
                clearInterval(interval);
                uploadArea.classList.remove('uploading');
                // 处理上传的文件
                filesArray.forEach(file => {
                    if (file.type.match('image.*')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const imageData = {
                                id: Date.now() + Math.random().toString(36).substr(2, 5),
                                src: e.target.result,
                                file: file
                            };
                            
                            uploadedImages.push(imageData);
                            addImagePreview(imageData);
                        };
                        
                        reader.readAsDataURL(file);
                    }
                });
            }
            uploadIndicator.style.width = `${progress}%`;
            uploadProgress.textContent = `上传中: ${progress}%`;
        }, 50);
    }

    // 添加图片预览
    function addImagePreview(imageData) {
        const preview = document.createElement('div');
        preview.className = 'image-preview';
        preview.dataset.id = imageData.id;
        
        const img = document.createElement('img');
        img.setAttribute('name', 'goodimg');
        img.src = imageData.src;
        img.alt = '商品图片';
        
        const deleteBtn = document.createElement('div');
        deleteBtn.className = 'delete-btn';
        deleteBtn.innerHTML = '<i class="fas fa-times"></i>';
        deleteBtn.addEventListener('click', () => {
            removeImage(imageData.id);
        });
        
        preview.appendChild(img);
        preview.appendChild(deleteBtn);
        previewContainer.appendChild(preview);
    }

    // 删除图片
    function removeImage(id) {
        uploadedImages = uploadedImages.filter(img => img.id !== id);
        
        const previewToRemove = document.querySelector(`.image-preview[data-id="${id}"]`);
        if (previewToRemove) {
            previewToRemove.style.opacity = '0';
            previewToRemove.style.transform = 'scale(0.8)';
            
            setTimeout(() => {
                previewToRemove.remove();
            }, 300);
        }
    }

    // 表单提交
    $('#productForm').on('submit', function(e) {
        e.preventDefault();
        
        // 清除之前的错误信息
        $('.is-invalid').removeClass('is-invalid');
        $('.invalid-feedback').remove();
        
        // 表单验证
        let isValid = true;
        const requiredFields = [
            'goodname', 'goodtype', 'goodprice', 
            'goodnum', 'gooddec', 'goodstat'
        ];
        
        // 检查必填字段
        requiredFields.forEach(field => {
            const element = $(`[name="${field}"]`);
            if (!element.val()) {
                isValid = false;
                element.addClass('is-invalid');
                element.after(`<div class="invalid-feedback">请填写此字段</div>`);
            }
        });
        
        // 检查交易方式是否选择
        const transactions = $('input[name="transactions"]:checked');
        if (transactions.length === 0) {
            isValid = false;
            $('.transactionSettings').addClass('is-invalid');
            if (!$('#transactionError').length) {
                $('.transactionSettings').first().closest('.mt-2')
                    .after(`<div id="transactionError" class="invalid-feedback d-block">请选择交易方式</div>`);
            }
        }
        
        // 检查运费设置是否选择
        const freightType = $('input[name="goodFreightType"]:checked');
        if (freightType.length === 0) {
            isValid = false;
            $('.shippingFee').addClass('is-invalid');
            if (!$('#freightError').length) {
                $('.shippingFee').first().closest('.mb-3')
                    .append(`<div id="freightError" class="invalid-feedback d-block">请选择运费设置</div>`);
            }
        }
        
        // 检查图片是否上传
        if (uploadedImages.length === 0) {
            isValid = false;
            uploadArea.classList.add('border', 'border-danger');
            if (!$('#imageError').length) {
                $(uploadArea).after(`<div id="imageError" class="invalid-feedback d-block">请上传商品图片</div>`);
            }
        } else {
            uploadArea.classList.remove('border', 'border-danger');
            $('#imageError').remove();
        }
        
        // 检查价格是否有效
        const goodprice = parseFloat($('input[name="goodprice"]').val());
        if (goodprice <= 0 || isNaN(goodprice)) {
            isValid = false;
            $('input[name="goodprice"]').addClass('is-invalid');
            $('input[name="goodprice"]').after(`<div class="invalid-feedback">价格必须大于0</div>`);
        }
        
        // 检查库存是否有效
        const goodnum = parseInt($('input[name="goodnum"]').val());
        if (goodnum <= 0 || isNaN(goodnum)) {
            isValid = false;
            $('input[name="goodnum"]').addClass('is-invalid');
            $('input[name="goodnum"]').after(`<div class="invalid-feedback">库存数量必须大于0</div>`);
        }
        
        if (!isValid) return;
        
        const formData = new FormData();
        const goodsId = $('input[name="goodsId"]').val();
        
        if (goodsId) {
            formData.append('goodsId', goodsId);
        }
        
        // 添加所有商品图片（最多5张）
        uploadedImages.forEach((image, index) => {
            formData.append(`goodsImage${index}`, image.file);
        });
        formData.append('imageCount', uploadedImages.length);
        
        // 使用jQuery选择器获取表单值
        formData.append('goodname', $('input[name="goodname"]').val());
        
        // 商品类型
        const goodtypeVal = $('select[name="goodtype"]').val();
        formData.append('goodtype', goodtypeVal);
        
        formData.append('goodprice', $('input[name="goodprice"]').val());
        
        // 原价处理（可为空）
        const oripriveVal = $('input[name="oriprive"]').val();
        if (oripriveVal) {
            formData.append('oriprive', oripriveVal);
        } else {
            formData.append('oriprive', '0');
        }
        
        formData.append('goodnum', $('input[name="goodnum"]').val());
        formData.append('gooddec', $('textarea[name="gooddec"]').val());
        
        // 新旧程度
        const goodstatVal = $('select[name="goodstat"]').val();
        formData.append('goodstat', goodstatVal);
        
        // 交易方式
        const transactionsValue = $('input[name="transactions"]:checked').val();
        formData.append('goodTradetType', transactionsValue);
        
        // 运费设置
        const freightTypeValue = $('input[name="goodFreightType"]:checked').val();
        formData.append('goodFreightType', freightTypeValue);
        
        const url = goodsId ? "/poj-java/updateGoods.do" : "/poj-java/addGoods.do";
        
        // 发送AJAX请求
        $.ajax({
            url: url,
            data: formData,
            type: "POST",
            processData: false,  
            contentType: false,   
            dataType: 'json',     
            beforeSend: function() {
                // 显示加载状态
                $('button[type="submit"]').prop('disabled', true)
                    .html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 发布中...');
            },
            success: function(data) {
                if (data && data.success) {
                	alert(goodsId ? '商品更新成功！' : '商品发布成功！');
                	window.location.href='mineInformation.jsp'
                    
                } else {
                    const errorMsg = data && data.message ? data.message : '未知错误';
                    alert('商品发布失败：' + errorMsg);
                }
            },
            error: function(xhr, status, error) {
                let errorMsg = "请求失败: "+error;
                
                // 尝试获取原始响应
                let rawResponse = '';
                try {
                    rawResponse = xhr.responseText || '';
                } catch (e) {
                    console.error("无法获取原始响应:", e);
                }
                
                if (xhr.status === 0) {
                    errorMsg += "无法连接到服务器";
                } else if (xhr.status === 404) {
                    errorMsg += "请求地址不存在";
                } else if (xhr.status === 500) {
                    errorMsg += "服务器内部错误";
                } else if (error === "parsererror") {
                    errorMsg += "解析响应失败";
                    
                    // 如果响应是纯文本（非JSON），显示部分内容
                    if (rawResponse) {
                        console.error("原始响应内容:", rawResponse);
                        errorMsg += `。响应内容: ${rawResponse.substring(0, 100)}...`;
                    }
                } else {
                    errorMsg += `${error} (状态码: ${xhr.status})`;
                }
                
                // 如果响应是JSON格式但解析失败，尝试手动解析
                if (rawResponse && rawResponse.trim().startsWith('{')) {
                    try {
                        const errorData = JSON.parse(rawResponse);
                        if (errorData.message) {
                            errorMsg = "服务器返回错误: " + errorData.message;
                        }
                    } catch (parseError) {
                        // 忽略解析错误
                    }
                }
                if (xhr.responseText) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        errorMsg = response.message || errorMsg;
                    } catch (e) {
                        errorMsg += "\n响应内容: " + xhr.responseText.substring(0, 100);
                    }
                }
                alert(errorMsg);
            },
            complete: function() {
                // 恢复按钮状态
                $('button[type="submit"]').prop('disabled', false)
                    .html('立即发布');
            }
        });
    });
    
    // 输入框实时验证
    $('input, select, textarea').on('input change', function() {
        if ($(this).val()) {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
        }
    });
    
    // 清除交易方式和运费设置的错误信息
    $('.transactionSettings, .shippingFee').on('change', function() {
        $('.transactionSettings').removeClass('is-invalid');
        $('#transactionError').remove();
        $('.shippingFee').removeClass('is-invalid');
        $('#freightError').remove();
    });
});